﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using EFong.View.Customer;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraBars;

namespace EFong.View.FlightTicket
{
    public partial class Frm_FlightTicketEdit : BasicForm
    {
        private Proxy.BaseServiceProxy _baseProxy { get { return Proxy.BaseServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy { get { return Proxy.MasterServiceProxy.GetInstance(); } }
        private Proxy.BusinessServiceProxy _businessProxy { get { return Proxy.BusinessServiceProxy.GetInstance(); } }

        public Contract.RFlightOrder ReturnValue = null;

        public Frm_FlightTicketEdit()
        {
            InitializeComponent();


            txt_Passenger.ReadOnly(true);
            txt_TicketOrderRef.ReadOnly(true);
            txt_TicketNo.ReadOnly(true);
            ckb_Keep.ReadOnly(true);
            txt_JourneyOrderType.ReadOnly(true);
            //txt_JourneyOrder.ReadOnly(true);
            //txt_InsuranceVendor.ReadOnly(true);
            txt_InsurancePoliceType.ReadOnly(true);
            cmb_InsurancePolice.ReadOnly(true);
            spe_Price.ReadOnly(true);
            spe_Tax1.ReadOnly(true);
            spe_Tax2.ReadOnly(true);
            spe_InsurancePolicePrice.ReadOnly(true);
            spe_InsuranceFee.ReadOnly(true);
            ckb_InsuranceFee.ReadOnly(true);
            spe_VendorDisount.ReadOnly(true);
            spe_Cost.ReadOnly(true);
            spe_NetPrice.ReadOnly(true);
            spe_Intergral.ReadOnly(true);
            spe_Discount.ReadOnly(true);

            spe_VendorDisount.SetValue(null);
            spe_Cost.SetValue(null);
            spe_NetPrice.SetValue(null);
            spe_Discount.SetValue(null);

            txt_Vendor.ReadOnly(true);
            txt_BankAccount.ReadOnly(true);
            txt_PaymentType.ReadOnly(true);
            txt_VendorCurrency.ReadOnly(true);
            spe_ExchangeRate.ReadOnly(true);

            cmb_JourneyType.ReadOnly(true);

            this.lct_BrowserReturn.Visibility = LayoutVisibility.Never;
        }

        protected override void InitFields()
        {
        }

        protected override void Events()
        {
            this.gv_Passengers.FocusedRowChanged += (s, e) =>
            {
                Detail = this.gv_Passengers.GetRow(e.FocusedRowHandle) as Contract.FlightOrderDatail;
            };
            this.btn_CustomerData.Click += (s, e) =>
            {
                editCustomer();
            };
            this.cmb_Customer.EditValueChanged += (s, e) =>
            {
                Contract.RCustomer customer = this.cmb_Customer.GetValue() as Contract.RCustomer;

                if (customer != null)
                {
                    SelCust = _masterProxy.GetCustomerByID(customer.ID).ReturnValue;
                }
                else
                {
                    SelCust = null;
                }
            };
            //this.txt_Vendor.EditValueChanged += (s, e) =>
            //{
            //    Contract.RVendor vendor = this.txt_Vendor.GetValue() as Contract.RVendor;

            //    if (vendor != null)
            //    {
            //        SelVend = _masterProxy.GetVendorByID(vendor.ID).ReturnValue;
            //    }
            //    else
            //    {
            //        SelVend = null;
            //    }
            //};

            //this.txt_PaymentType.SelectedIndexChanged += (s, e) =>
            //    {
            //        if (ViewState == ViewStates.EDIT) { return; }

            //        this.txt_BankAccount.SetValue(default(Contract.BankAccount));
            //        this.txt_BankAccount.ReadOnly(this.txt_PaymentType.SelectedIndex <= 0);

            //        if (this.txt_PaymentType.SelectedIndex == 0)
            //            this.txt_VendorCurrency.SetValue(_baseProxy.GetCNYCurrency().ReturnValue);
            //    };
            //this.txt_BankAccount.SelectedIndexChanged += (s, e) =>
            //    {
            //        Contract.BankAccount bank = this.txt_BankAccount.GetValue() as Contract.BankAccount;
            //        if (bank != null)
            //            this.txt_VendorCurrency.SetValue(bank.Currency);
            //        else
            //            this.txt_VendorCurrency.SetValue(default(Contract.Currency));
            //    };

            this.btn_BrowserReturn.Click += (s, e) =>
                {
                    if (Detail == null)
                        return;
                    if (Detail.Status != "已退票")
                        return;

                    Frm_FlightTicketReturn frm = new Frm_FlightTicketReturn();
                    frm.ViewState = ViewStates.BROWSER;
                    frm.Load += (s1, e1) =>
                    {                        
                        Contract.FlightReturn flightReturn = Detail.FlightReturnHis[0];
                        flightReturn.FlightOrderDetail = Detail;
                        flightReturn.Currency = Order.Currency;
                        flightReturn.Customer = Order.Customer;
                        flightReturn.VendorCurrency = Order.VendorCurrency;
                        flightReturn.Currency = Order.Currency;
                        frm.Detail = flightReturn;
                    };
                    FormOpener.ShowDialog(frm);
                };
        }

        protected override void LoadDatas()
        {
            this.bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            //this.bds_Vendor.BindingData(_masterProxy.GetAllFlightVendor().ReturnValue);
            this.cmb_OrderTicketUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_ProvideTicketUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_OrderUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_SalesMan.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);

            //this.txt_BankAccount.Properties.BindingData(_masterProxy.GetAllEffectivedBankAccount());
            //this.txt_VendorCurrency.Properties.BindingData(_baseProxy.GetAllCurrency().ReturnValue);

            if (this.cmb_OrderUser.GetValue() == null)
                this.cmb_OrderUser.SetValue(AppParameters.LoginUser);

        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Add":
                    this.add();
                    break;
                case "bbt_AddBySameJiurney":
                    this.addBySameJiurney();
                    break;
                case "bbt_Edit":
                    this.edit();
                    break;
                case "bbt_Save":
                    this.save();
                    break;
                case "bbt_Change":
                    this.detailChange();
                    break;
                case "bbt_Return":
                    this.detailReturn();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void detailReturn()
        {
            if (Detail == null)
                return;
            if (Detail.Status == "已退票")
                return;

            Frm_FlightTicketReturn frm = new Frm_FlightTicketReturn();
            frm.Load += (s, e) =>
            {
                frm.Detail = new Contract.FlightReturn()
                    {
                        FlightOrderDetail = Detail,
                        Currency = Order.Currency,
                        VendorCurrency = Detail.VendorCurrency,
                        Customer = Order.Customer,
                        Vendor = Detail.Vendor
                    };
                frm.Order = Order;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                Detail.Status = "已退票";
                Detail.FlightReturnHis.Add(frm.Detail);
                Contract.RFlightReturn rReturn = new Contract.RFlightReturn
                {
                    PassengerCName = Detail.Passenger.CName,
                    PassengerEName = Detail.Passenger.EName,
                    OrderDate = frm.Detail.OrderDate.Value,
                    CustomerReturnPrice = frm.Detail.CustomerReturnPrice
                };

                //this.gv_ReturnHis.BeginDataUpdate();
                bds_flightReturn.Add(rReturn);
                //this.gv_ReturnHis.EndDataUpdate();
                updateReturn();
            }
        }

        private void detailChange()
        {
            if (Detail == null)
                return;

            Frm_FlightTicketChange frm = new Frm_FlightTicketChange();
            frm.Load += (s, e) =>
            {
                frm.Detail = new Contract.FlightChange()
                    {
                        Currency = Order.Currency,
                        VendorCurrency = Detail.VendorCurrency,
                        Customer = Order.Customer,
                        Vendor = Detail.Vendor
                    };
                frm.Order = Order;
                frm.OrderDetail = Detail;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                Contract.RFlightChange rChange = new Contract.RFlightChange
                {
                    PassengerCName = Detail.Passenger.CName,
                    PassengerEName = Detail.Passenger.EName,
                    OrderDate = frm.Detail.OrderDate.Value,
                    Price = frm.Detail.Price,
                    VendorPrice = frm.Detail.VendorPrice
                };
                this.gv_ChangeHis.BeginDataUpdate();
                bds_flightChange.Add(rChange);
                this.gv_ChangeHis.EndDataUpdate();
                updateChange();
            }
        }

        private void add()
        {
            Frm_FlightTicketDetailEdit frm = new Frm_FlightTicketDetailEdit();
            frm.Text = "增加订单明细";
            frm.ViewState = this.ViewState;
            frm.Load += (s, e) =>
            {
                frm.Detail = new Contract.FlightOrderDatail() { FlightOrder = getOrder() };
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Passengers.BeginDataUpdate();
                ((List<Contract.FlightOrderDatail>)this.bds_flightOrderDatail.DataSource).Add(frm.Detail);
                this.gv_Passengers.EndDataUpdate();
                updateOrderTotalFields();
            }
        }

        private void addBySameJiurney()
        {
            if (Detail == null)
                return;

            Frm_FlightTicketDetailEdit frm = new Frm_FlightTicketDetailEdit();
            frm.Text = "增加订单明细";
            frm.ViewState = this.ViewState;
            frm.Load += (s, e) =>
            {
                Contract.FlightOrderDatail newDetail = new Contract.FlightOrderDatail()
                {
                    FlightOrder = getOrder(),
                    //FlightWayList = Detail.FlightWayList,
                    Price = Detail.Price,
                    Tax1 = Detail.Tax1,
                    Tax2 = Detail.Tax2,
                    VendorDiscount = Detail.VendorDiscount,
                    Cost = Detail.Cost,
                    NetPrice = Detail.NetPrice,
                    Vendor = Detail.Vendor,
                    PaymentType = Detail.PaymentType,
                    BankAccount = Detail.BankAccount,
                    VendorCurrency = Detail.VendorCurrency,
                    ExchangeRate = Detail.ExchangeRate,
                    AirwaysOrderNo = Detail.AirwaysOrderNo,
                    TicketNo = Detail.TicketNo,
                    Discount = Detail.Discount,
                };



                //if (Detail.FlightWayList.Count == 0)
                //{
                //    frm.cmb_JourneyType.SelectedIndex = -1;
                //}
                //else if (Detail.FlightWayList.Count == 1)
                //{
                //    frm.cmb_JourneyType.SelectedIndex = 0;
                //}
                //else if (Detail.FlightWayList.Count == 2 && ((Contract.FlightWay)Detail.FlightWayList[0]).DepartLocation == ((Contract.FlightWay)Detail.FlightWayList[1]).Destination &&
                //        ((Contract.FlightWay)Detail.FlightWayList[0]).Destination == ((Contract.FlightWay)Detail.FlightWayList[1]).DepartLocation)
                //{
                //    frm.cmb_JourneyType.SelectedIndex = 1;
                //}
                //else
                //{
                //    frm.cmb_JourneyType.SelectedIndex = 2;
                //}

                foreach (Contract.FlightWay flightWay in Detail.FlightWayList)
                {
                    Contract.FlightWay newFlightWay = new Contract.FlightWay()
                    {
                        DepartDate = flightWay.DepartDate,
                        DepartLocation = flightWay.DepartLocation,
                        Destination = flightWay.Destination,
                        FlightNo = flightWay.FlightNo,
                        IsDelete = flightWay.IsDelete,
                        Seat = flightWay.Seat,
                        出发时间 = flightWay.出发时间
                    };

                    newDetail.FlightWayList.Add(newFlightWay);
                }

                frm.Detail = newDetail;

                if (Detail.JourneyOrderList.Count > 0)
                    frm.cmb_JourneyOrderType.SetValue(Detail.JourneyOrderList[0].Type);
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Passengers.BeginDataUpdate();
                ((List<Contract.FlightOrderDatail>)this.bds_flightOrderDatail.DataSource).Add(frm.Detail);
                this.gv_Passengers.EndDataUpdate();
                updateOrderTotalFields();
            }
        }

        private void edit()
        {
            if (Detail == null)
                return;

            Frm_FlightTicketDetailEdit frm = new Frm_FlightTicketDetailEdit();
            frm.Text = "修改订单明细";
            frm.ViewState = this.ViewState;
            frm.Load += (s, e) =>
            {
                frm.Detail = Detail;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Passengers.BeginDataUpdate();
                this.gv_Passengers.EndDataUpdate();
                Detail = frm.Detail;
                updateOrderTotalFields();
            }
        }

        private string returnRef;

        private void save()
        {
            Contract.FlightOrder order = null;

            UIOperManager.SaveData(
                () =>
                {
                    return true;
                },
                () =>
                {
                    order = getOrder();
                    updateToOrder(order);
                    var result = _businessProxy.UpdateFlightOrder(Order);

                    if (result.IsSuccess)
                    {
                        returnRef = result.ReturnValue;
                        this.txt_OrderRef.Text = returnRef;
                    }

                    return result.IsSuccess;
                },
                string.Empty,
                () =>
                {
                    DialogResult = DialogResult.OK;
                    MsgBox.Info(string.Format("{0} 保存成功", returnRef));
                    this.Close();

                    ReturnValue = new Contract.RFlightOrder()
                    {
                        ID = Order.ID,
                        Customer = Order.Customer.Name,
                        CustomerStatus = Order.CustomerStatus,
                        Intergral = Order.TotalIntergral.Value,
                        OrderDate = Order.OrderDate,
                        OrderUserText = Order.OrderUser.Name,
                        Ref = returnRef,
                        Remark = Order.Remark,
                        Status = Order.Status,
                        TotalPrice = Order.TotalAccountReceivable,
                        VendorStatus = Order.VendorStatus
                    };
                });
        }


        private void editCustomer()
        {
            if (SelCust == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            if (!AppParameters.AllowEditCustomer)
                frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
            {
                frm.CurCust = SelCust;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
                SelCust = frm.CurCust;
        }

        private void updateOrderTotalFields()
        {
            Contract.FlightOrder order = getOrder();

            this.txt_OrderTotalPrice.SetText(order.TotalAccountReceivable);
            this.txt_OrderTotalProfit.SetText(order.TotalProfit);
            this.txt_OrderTotalVendorPrice.SetText(order.TotalAccountPayable);
            this.txt_OrderTotalIntegral.SetText(order.TotalIntergral);
        }

        #region Order
        // current FlightOrder
        private Contract.FlightOrder _order;
        public Contract.FlightOrder Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
            }
            else
            {
                if (Order.OrderUser != null)
                    this.cmb_OrderUser.SetValue(Order.OrderUser);
                if (Order.OrderDate != null)
                    this.dteOrderDate.SetValue(Order.OrderDate);
                this.txt_OrderRef.SetText(Order.Ref);
                if (Order.Ref == string.Empty)
                    this.txt_OrderRef.SetText("(保存时自动获取)");

                this.cmb_Customer.SetValue(Order.Customer);
                SelCust = Order.Customer;
                //this.txt_Vendor.SetValue(Order.Vendor);
                //SelVend = Order.Vendor;
                this.cmb_SalesMan.SetValue(Order.Salesman);

                this.cmb_CreditTerm.SetValue(Order.CreditTerm);

                //this.spe_ExchangeRate.SetValue(Order.ExchangeRate);
                this.spe_PrintTotalPrice.SetValue(Order.PrintTotalPrice);
                this.txt_OrderRemark.SetText(Order.Remark);

                this.dte_ProvideTicketDate.SetValue(Order.ProvideTicketDate);
                this.dte_DeliveryTicketDate.SetValue(Order.DeliveryDate);

                cmb_OrderTicketUser.SetValue(Order.OrderTicketUser);
                cmb_ProvideTicketUser.SetValue(Order.ProvideTicketUser);

                rad_International.SetValue(Order.IsInternational);

                this.txt_Address.SetText(Order.Address);

                //this.txt_PaymentType.SetDisplay(Order.PaymentType);
                //if (Order.BankAccount != null)
                //    this.txt_BankAccount.SetValue(Order.BankAccount);
                //if (Order.VendorCurrency != null)
                //    this.txt_VendorCurrency.SetValue(Order.VendorCurrency);

                this.txt_OrderTotalPrice.SetText(Order.TotalAccountReceivable);
                this.txt_OrderTotalProfit.SetText(Order.TotalProfit);
                this.txt_OrderTotalVendorPrice.SetText(Order.TotalAccountPayable);
                this.txt_OrderTotalIntegral.SetText(Order.TotalIntergral);


                txt_CPerson.SetText(Order.ContactPerson);
                txt_CPersonTel.SetText(Order.联系电话);
                txt_CPersonPhone.SetText(Order.移动电话);


                this.bds_flightOrderDatail.BindingData(Order.Details);

                this.bds_flightReturn.BindingData(Order.FlightReturnHis);
                updateReturn();

                this.bds_flightChange.BindingData(Order.FlightChangeHis);
                updateChange();
            }
        }

        private void updateReturn()
        {
            if (Detail != null)
                this.lct_BrowserReturn.Visibility = Detail.Status == "已退票" ? LayoutVisibility.Always : LayoutVisibility.Never;
            else
                this.lct_BrowserReturn.Visibility = LayoutVisibility.Never;
            //lcg_Return.Visibility = this.bds_flightReturn.Count > 0 ? LayoutVisibility.Always : LayoutVisibility.Never;
            if (ChangedOrReturnedAction != null)
                ChangedOrReturnedAction.Invoke();
        }

        private void updateChange()
        {
            lcg_Change.Visibility = this.bds_flightChange.Count > 0 ? LayoutVisibility.Always : LayoutVisibility.Never;
            if (ChangedOrReturnedAction != null)
                ChangedOrReturnedAction.Invoke();
        }

        private Contract.FlightOrder getOrder()
        {
            Contract.FlightOrder order = new Contract.FlightOrder();

            order.OrderUser = this.cmb_OrderUser.GetValue() as Contract.User;
            if (this.dteOrderDate.GetValue().HasValue)
                order.OrderDate = this.dteOrderDate.GetValue().Value;
            order.Customer = SelCust;
            //order.Vendor = SelVend;
            order.OrderTicketUser = this.cmb_OrderTicketUser.GetValue() as Contract.User;
            order.ProvideTicketUser = this.cmb_ProvideTicketUser.GetValue() as Contract.User;
            order.CreditTerm = this.cmb_CreditTerm.GetDisplay();
            //order.ExchangeRate = this.spe_ExchangeRate.GetValue();
            order.PrintTotalPrice = this.spe_PrintTotalPrice.GetValue(true);
            order.Remark = this.txt_OrderRemark.GetText();
            order.Details = this.bds_flightOrderDatail.DataSource as List<Contract.FlightOrderDatail>;
            order.Salesman = this.cmb_SalesMan.GetValue() as Contract.User;
            order.Currency = _baseProxy.GetCNYCurrency().ReturnValue;
            order.Address = this.txt_Address.GetText();
            order.IsInternational = rad_International.GetValue();

            //order.BankAccount = this.txt_BankAccount.GetValue() as Contract.BankAccount;
            //order.PaymentType = this.txt_PaymentType.GetDisplay();
            //order.VendorCurrency = this.txt_VendorCurrency.GetValue() as Contract.Currency;

            order.ContactPerson = txt_CPerson.GetText();
            order.联系电话 = txt_CPersonTel.GetText();
            order.移动电话 = txt_CPersonPhone.GetText();

            if (this.dte_ProvideTicketDate.GetValue().HasValue)
                order.ProvideTicketDate = this.dte_ProvideTicketDate.GetValue().Value;

            if (this.dte_DeliveryTicketDate.GetValue().HasValue)
                order.DeliveryDate = this.dte_DeliveryTicketDate.GetValue().Value;

            return order;
        }

        private void updateToOrder(Contract.FlightOrder order)
        {
            Order.Customer = order.Customer;
            Order.Details = order.Details;
            //Order.ExchangeRate = order.ExchangeRate;
            Order.OrderDate = order.OrderDate;
            Order.OrderTicketUser = order.OrderTicketUser;
            Order.OrderUser = order.OrderUser;
            Order.CreditTerm = order.CreditTerm;
            Order.PrintTotalPrice = order.PrintTotalPrice;
            Order.Remark = order.Remark;
            //Order.Vendor = order.Vendor;
            Order.Salesman = order.Salesman;
            Order.Currency = order.Currency;
            Order.DeliveryDate = order.DeliveryDate;
            Order.ProvideTicketDate = order.ProvideTicketDate;
            Order.ProvideTicketUser = order.ProvideTicketUser;
            Order.Address = order.Address;
            Order.IsInternational = order.IsInternational;

            Order.ContactPerson = order.ContactPerson;
            Order.ContactPersonTel = order.ContactPersonTel;
            Order.联系电话 = order.联系电话;
            Order.移动电话 = order.移动电话;

            //Order.PaymentType = order.PaymentType;
            //Order.BankAccount = order.BankAccount;
            //Order.VendorCurrency = order.VendorCurrency;


            foreach (var detail in Order.Details)
            {
                detail.FlightOrder = Order;
            }
        }
        #endregion

        #region Detail
        private Contract.FlightOrderDatail _detail;
        public Contract.FlightOrderDatail Detail
        {
            get { return _detail; }
            set
            {
                _detail = value;
                onDetailChanged();
            }
        }

        private void onDetailChanged()
        {
            if (Detail == null)
            {
                this.bds_flightWay.BindingData(typeof(Contract.FlightWay));
                setJourneyType();

                Passenger = null;
                this.cmb_JourneyOrder.Properties.BindingData(null);
                this.cmb_InsurancePolice.Properties.BindingData(null);
                //JourneyOrder = null;
                //InsurancePolicy = null;
                ControlExtensions.ClearValue(
                    txt_TicketOrderRef,
                    txt_TicketNo,
                    spe_Price,
                    spe_Tax1,
                    spe_Tax2,
                    spe_InsuranceFee,
                    spe_VendorDisount,
                    spe_Cost,
                    spe_NetPrice,
                    spe_Discount,
                    txt_TotalPrice,
                    txt_TotalProfit,
                    txt_TotalVendorPrice,
                    spe_Intergral,
                    cmb_JourneyType,
                    cmb_JourneyOrder,
                    cmb_InsurancePolice
                    );

                ckb_InsuranceFee.SetValue(false);
                ckb_Keep.SetValue(false);
            }
            else
            {
                this.bds_flightWay.BindingData(Detail.FlightWayList.FilterIsDelFlightWays());
                setJourneyType();

                Passenger = Detail.Passenger;

                txt_TicketOrderRef.SetText(Detail.AirwaysOrderNo);
                txt_TicketNo.SetText(Detail.TicketNo);

                if (Detail.Status == "留用")
                    ckb_Keep.SetValue(true);

                //JourneyOrder = Detail.JourneyOrder;

                //InsurancePolicy = Detail.InsurancePolicy;

                spe_Price.SetValue(Detail.Price);
                spe_Tax1.SetValue(Detail.Tax1);
                spe_Tax2.SetValue(Detail.Tax2);
                spe_InsuranceFee.SetValue(Detail.InsuranceFee);
                ckb_InsuranceFee.SetValue(Detail.IsInsurancePolicyFree);
                spe_VendorDisount.SetValue(Detail.VendorDiscount);
                spe_Cost.SetValue(Detail.Cost);
                spe_NetPrice.SetValue(Detail.NetPrice);
                spe_Intergral.SetValue(Detail.Intergral);
                spe_Discount.SetValue(Detail.Discount);

                spe_ExchangeRate.SetValue(Detail.ExchangeRate);
                txt_Vendor.SetText(Detail.Vendor);
                txt_PaymentType.SetText(Detail.PaymentType);
                txt_BankAccount.SetText(Detail.BankAccount);
                txt_VendorCurrency.SetText(Detail.VendorCurrency);

                this.txt_TotalPrice.SetText(Detail.AccountReceivable);
                this.txt_TotalProfit.SetText(Detail.Profit);
                this.txt_TotalVendorPrice.SetText(Detail.AccountPayable);

                this.lct_BrowserReturn.Visibility = Detail.Status == "已退票" ? LayoutVisibility.Always : LayoutVisibility.Never;

                if (Detail.JourneyOrderList.Count > 0)
                {
                    txt_JourneyOrderType.SetText(Detail.JourneyOrderList[0].Type);
                }
                else
                {
                    txt_JourneyOrderType.SetText(string.Empty);
                }
                cmb_JourneyOrder.Properties.BindingData<Contract.JourneyOrder>(Detail.JourneyOrderList, (item) => { return true; });

                if (Detail.InsurancePolicyList.Count > 0)
                {
                    txt_InsurancePoliceType.SetText(Detail.InsurancePolicyList[0].Type);

                }
                else
                {
                    txt_InsurancePoliceType.SetText(string.Empty);
                }
                cmb_InsurancePolice.Properties.BindingData<Contract.InsurancePolicy>(Detail.InsurancePolicyList, (item) => { return true; });
            }
        }

        private void setJourneyType()
        {
            if (bds_flightWay.Count == 0)
            {
                this.cmb_JourneyType.SelectedIndex = -1;
            }
            else if (bds_flightWay.Count == 1)
            {
                this.cmb_JourneyType.SelectedIndex = 0;
            }
            else if (bds_flightWay.Count == 2 && ((Contract.FlightWay)bds_flightWay[0]).DepartLocation == ((Contract.FlightWay)bds_flightWay[1]).Destination &&
                    ((Contract.FlightWay)bds_flightWay[0]).Destination == ((Contract.FlightWay)bds_flightWay[1]).DepartLocation)
            {
                this.cmb_JourneyType.SelectedIndex = 1;
            }
            else
            {
                this.cmb_JourneyType.SelectedIndex = 2;
            }
        }

        #endregion

        #region Passenger
        private Contract.Passenger _passenger;
        public Contract.Passenger Passenger
        {
            get { return _passenger; }
            set
            {
                _passenger = value;
                onPassengerChanged();
            }
        }

        private void onPassengerChanged()
        {
            if (Passenger == null)
            {
                ControlExtensions.ClearValue(
                    txt_Passenger,
                    txt_Sex,
                    txt_Phone,
                    txt_IDCard);
            }
            else
            {
                txt_Passenger.SetText(Passenger);
                txt_Sex.SetText(Passenger.Sex);

                string phote = string.Empty;
                if (!string.IsNullOrEmpty(Passenger.Tel1) && !string.IsNullOrEmpty(Passenger.Tel2))
                    phote = string.Format("{0} ; {1}", Passenger.Tel1, Passenger.Tel2);
                else
                    phote = string.IsNullOrEmpty(Passenger.Tel1) ? Passenger.Tel2 : Passenger.Tel1;

                txt_Phone.SetText(phote);

                string idCard = string.Empty;
                if (!string.IsNullOrEmpty(Passenger.IDCardNr1) && !string.IsNullOrEmpty(Passenger.IDCardNr2))
                    idCard = string.Format("{0} ; {1}", Passenger.IDCardNr1, Passenger.IDCardNr2);
                else
                    idCard = string.IsNullOrEmpty(Passenger.IDCardNr1) ? Passenger.IDCardNr2 : Passenger.IDCardNr1;

                txt_IDCard.SetText(idCard);
            }
        }
        #endregion

        #region JourneyOrder
        //private Contract.JourneyOrder _journeyOrder;
        //public Contract.JourneyOrder JourneyOrder
        //{
        //    get { return _journeyOrder; }
        //    set
        //    {
        //        _journeyOrder = value;
        //        onJourneyOrderChanged();
        //    }
        //}

        //private void onJourneyOrderChanged()
        //{
        //    if (JourneyOrder == null)
        //    {
        //        ControlExtensions.ClearValue(
        //            txt_JourneyOrderType,
        //            txt_JourneyOrder
        //            );
        //    }
        //    else
        //    {
        //        txt_JourneyOrderType.SetText(JourneyOrder.Type);
        //        txt_JourneyOrder.SetText(JourneyOrder.Ref);
        //    }
        //}
        #endregion

        #region InsurancePolicy
        //private Contract.InsurancePolicy _insurancePolicy;
        //public Contract.InsurancePolicy InsurancePolicy
        //{
        //    get { return _insurancePolicy; }
        //    set
        //    {
        //        _insurancePolicy = value;
        //        onInsurancePolicyChanged();
        //    }
        //}

        //private void onInsurancePolicyChanged()
        //{
        //    if (InsurancePolicy == null)
        //    {
        //        ControlExtensions.ClearValue(
        //            txt_InsuranceVendor,
        //            txt_InsurancePoliceType,
        //            cmb_InsurancePolice,
        //            spe_InsurancePolicePrice
        //            );
        //    }
        //    else
        //    {
        //        //txt_InsuranceVendor.SetText(Detail.InsurancePolicy.Vendor);
        //        //txt_InsurancePoliceType.SetText(Detail.InsurancePolicy.Type);
        //        //txt_InsurancePolice.SetText(Detail.InsurancePolicy.Ref);
        //        //spe_InsurancePolicePrice.SetValue(Detail.InsurancePolicy.BasePrice);
        //    }
        //}
        #endregion

        #region Vendor
        //public Contract.Vendor SelVend { get; set; }
        #endregion

        #region Customer
        private Contract.Customer _selCust;
        public Contract.Customer SelCust
        {
            get { return _selCust; }
            set
            {
                _selCust = value;
                onSelCustChanged();
            }
        }

        private void onSelCustChanged()
        {
            if (SelCust == null)
            {
                this.cmb_SalesMan.SetValue(default(Contract.User));
                this.txt_Address.SetText(null);
                this.txt_CPerson.SetText(null);
                this.txt_CPersonTel.SetText(null);
                this.txt_CPersonPhone.SetText(null);
            }
            else
            {
                this.cmb_SalesMan.SetValue(SelCust.Salesman);
                this.txt_Address.SetText(SelCust.Address);
                this.txt_CPerson.SetText(SelCust.ContactPerson1);
                this.txt_CPersonTel.SetText(SelCust.ContactPerson1Tel);
                this.txt_CPersonPhone.SetText(SelCust.ContactPerson1Phone1);
            }
        }
        #endregion


        public Action ChangedOrReturnedAction { get; set; }

        protected override void OnViewStateChanged()
        {
            switch (ViewState)
            {
                case ViewStates.ADD:
                    bbt_Add.Visibility = BarItemVisibility.Always;
                    bbt_AddBySameJiurney.Visibility = BarItemVisibility.Always;
                    bbt_Change.Visibility = BarItemVisibility.Never;
                    bbt_Return.Visibility = BarItemVisibility.Never;
                    break;
                case ViewStates.EDIT:
                    bbt_Add.Visibility = BarItemVisibility.Never;
                    bbt_AddBySameJiurney.Visibility = BarItemVisibility.Never;
                    bbt_Change.Visibility = BarItemVisibility.Always;
                    bbt_Return.Visibility = BarItemVisibility.Always;

                    if (!AppParameters.IsAdRole)
                    {
                        cmb_CreditTerm.ReadOnly(true);
                        cmb_Customer.ReadOnly(true);
                        rad_Internal.ReadOnly(true);
                        rad_International.ReadOnly(true);
                    }
                    break;
                default:
                    break;
            }
        }

        private void dteOrderDate_TextChanged(object sender, EventArgs e)
        {
            int i = 0;
            i++;
        }

    }
}
